// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------

const fs = require('fs');
module.exports = class extends think.cmswing.admin {
  /**
     * index action
     * @return {Promise} []
     */
  constructor(ctx) {
    super(ctx); // 调用父级的 constructor 方法，并把 ctx 传递进去
    // 其他额外的操作
    this.db = this.model('cmswing/member');
    this.tactive = 'member';
  }

  /**
     * 用户首页
     * @returns {*}
     */

  async indexAction () {
    const map = { 'status': ['>', -1], is_admin: 0 };
    /* if (!think.isEmpty(this.get('q'))) {
      map['username|real_name'] = ['like', '%' + this.get('q') + '%'];
    }
    if (!think.isEmpty(this.get('groupid'))) {
      map['groupid'] = ['IN', this.get('groupid').replace(/\s/g, ',')];
    } */
    if (!think.isEmpty(this.get('real_name'))) {
      map.real_name = ['like', '%' + this.get('real_name') + '%'];
    }
    if (!think.isEmpty(this.get('mobile'))) {
      map.mobile = this.get('mobile');
    }
    if (!think.isEmpty(this.get('gsmc'))) {
      map.gsmc = ['like', '%' + this.get('gsmc') + '%'];
    }
    if (!think.isEmpty(this.get('groupid'))) {
      map.groupid = this.get('groupid');
    }
    const data = await this.db.where(map).page(this.get('page') || 1, 20).order('id DESC').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '用户列表';
    // 获取管理组
    const role = this.model('auth_role').where({ status: 1 }).select();
    this.assign('role', role);
    // 会员组
    const usergroup = await this.model('member_group').select();
    this.assign('usergroup', usergroup);
    return this.display();
  }

  async userlistAction () {
    // 用户列表
    const gets = this.get();
    const start = parseInt(gets.start);
    const length = parseInt(gets.length);
    const draw = gets.draw;
    const key = gets['search[value]'];
    const userList = await this.db.join({
      table: 'customer',
      join: 'left',
      as: 'u',
      on: ['id', 'user_id']
    }).field('id,username,score,login,last_login_ip,last_login_time,status,u.real_name,u.group_id,u.balance').limit(start, length).where({ username: ['like', '%' + key + '%'], status: ['>', -1] }).order('id DESC').countSelect();
    userList.data.forEach(v => {
      v.last_login_time = times(v.last_login_time);
      v.last_login_ip = _int2iP(v.last_login_ip);
    });
    // console.log(userList)
    const data = {
      'draw': draw,
      'recordsTotal': userList.count,
      'recordsFiltered': userList.count,
      'data': userList.data
    };
    return this.json(data);
  }

  async orgAction () {
    const zzjgList = await this.model('zzjg').select();
    const zzjgId = [];
    const zzjgName = [];
    let orgData = null;
    const level3 = [];
    for (let index = 0; index < zzjgList.length; index++) {
      const zzjg = zzjgList[index];
      zzjg.name = zzjg.zzjg;
      Object.assign(zzjg, {
        symbol: 'circle',
        symbolSize: [zzjg.pid!=0?40:60, zzjg.pid!=0?40:60],
        itemStyle: {
          normal: {
            color:'#77f177',
            label: {
              position: zzjg.pid!=0?'left':'top'
            }
          }
        }
      });
      zzjgId.push(zzjg.id);
      zzjgName.push(zzjg.zzjg);
      zzjg._id = zzjg.id;
      zzjg.id = 'z_' + zzjg.id;
      if (zzjg.pid != 0) {
        level3.push({
          id: zzjg.id + '_0',
          name: '前台',
          pid: zzjg.id,
          symbol: 'circle',
          symbolSize: [35, 35],
          itemStyle: {
            normal: {
              color:'#ff9800',
              label: {
                position:'left'
              }
            }
          }
        });
        level3.push({
          id: zzjg.id + '_1',
          name: '后台',
          pid: zzjg.id,
          symbol: 'circle',
          symbolSize: [35, 35],
          itemStyle: {
            normal: {
              color:'#ff9800',
              label: {
                position:'left'
              }
            }
          }
        });
      }
      zzjg.pid = 'z_' + zzjg.pid;
    }

    const memberList = await this.model('member').where({ gsmc: ['in', zzjgName], zzjg: ['in', zzjgId], _logic: 'OR' }).field('id,username,real_name,gsmc,zzjg,is_admin').select();

    for (let index = 0; index < memberList.length; index++) {
      const member = memberList[index];

      const resIndex = zzjgList.findIndex((item) => {
        return item._id == member.zzjg || item.name == member.gsmc;
      });
      if (resIndex != -1) {
        member.pid = zzjgList[resIndex].id + '_' + member.is_admin
        member.name = member.real_name || member.username
      }
      Object.assign(member, {
        symbol: 'circle',
        symbolSize: [30, 30],
        itemStyle: {
          normal: {
            label: {
              position:'bottom'
            }
          }
        }
      });
    }
    let list = zzjgList.concat(level3).concat(memberList);
    orgData = arr_to_tree(list, 'z_0')
    // function geneOrgHtml (data) {
    //   if (!data || data.length < 1) return '';
    //   let html = '<ul>';
    //   for (let index = 0; index < data.length; index++) {
    //     const element = data[index];
    //     html += '<li>' + element.name + geneOrgHtml(element.children) + '</li>';
    //   }
    //   html += '</ul>';
    //   return html;
    // }
    //const orgHtml = geneOrgHtml(orgData);
    this.assign('orgData', JSON.stringify(orgData));
    return this.display();
  }

  async shenhelistAction () {
    // 用户列表
    const gets = this.get();
    const start = parseInt(gets.start);
    const length = parseInt(gets.length);
    const draw = gets.draw;
    const key = gets['search[value]'];
    const userList = await this.db.join({
      table: 'customer',
      join: 'left',
      as: 'u',
      on: ['id', 'user_id']
    }).field('id,username,score,login,last_login_ip,last_login_time,status,u.real_name,u.group_id,u.balance').limit(start, length).where({ username: ['like', '%' + key + '%'], status: ['>', -1] }).order('id DESC').countSelect();
    userList.data.forEach(v => {
      v.last_login_time = times(v.last_login_time);
      v.last_login_ip = _int2iP(v.last_login_ip);
    });
    // console.log(userList)
    const data = {
      'draw': draw,
      'recordsTotal': userList.count,
      'recordsFiltered': userList.count,
      'data': userList.data
    };
    return this.json(data);
  }

  async shenheAction () {
    const map = { 'status': ['>', -1], is_admin: 0 };
    let { zhucestatus } = this.get();
    if (think.isEmpty(zhucestatus)) {
      zhucestatus = 1;
      this.assign('zhucestatus', zhucestatus);
    } else if (zhucestatus == 3) {
      this.assign('zhucestatus', zhucestatus);
      zhucestatus = ['in', [-1, 2]];
    } else if (zhucestatus == 1) {
      zhucestatus = 1;
      this.assign('zhucestatus', zhucestatus);
    } else {
      return this.fail('参数传递错误！');
    }
    map.zhucestatus = zhucestatus;
    if (!think.isEmpty(this.get('real_name'))) {
      map.real_name = ['like', '%' + this.get('real_name') + '%'];
    }
    if (!think.isEmpty(this.get('mobile'))) {
      map.mobile = this.get('mobile');
    }
    if (!think.isEmpty(this.get('gsmc'))) {
      map.gsmc = ['like', '%' + this.get('gsmc') + '%'];
    }
    if (!think.isEmpty(this.get('groupid'))) {
      map.groupid = this.get('groupid');
    }
    const data = await this.db.where(map).page(this.get('page') || 1, 20).order('id DESC').countSelect();
    console.log('url=' + JSON.stringify(data.data).sfzzmpic);
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    console.log('data.data=' + JSON.stringify(data.data));
    this.meta_title = '用户列表';
    // 获取管理组
    const role = this.model('auth_role').where({ status: 1 }).select();
    this.assign('role', role);
    return this.display();
  }
  // 会员注销列表
  async cancellistAction () {
    /* const map = {'status': -1,is_admin:0};
    if (!think.isEmpty(this.get('real_name'))) {
      map.real_name = ['like', '%' + this.get('real_name') + '%'];
    }
    if (!think.isEmpty(this.get('mobile'))) {
      map.mobile = this.get('mobile');
    }
    if (!think.isEmpty(this.get('gsmc'))) {
      map.gsmc = ['like', '%' + this.get('gsmc') + '%'];
    }
    if (!think.isEmpty(this.get('groupid'))) {
      map.groupid = this.get('groupid') ;
    } */
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.status = -1;
    map.is_admin = 0;
    map.cancel_remark_id = ['!=', null];
    const data = await this.db.where(map).page(this.get('page') || 1, 20).order('id DESC').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '用户列表';
    // 获取管理组
    const role = this.model('auth_role').where({ status: 1 }).select();
    this.assign('role', role);
    return this.display();
  }

  /**
     * 会员充值
     */
  async rechargeAction () {
    if (this.isAjax('POST')) {
      const data = this.post();
      const self = this;
      const insertId = await this.db.transaction(async () => {
        await self.db.where({ id: data.id }).increment('amount', data.balance);
        const amount_log = await self.db.where({ id: data.id }).getField('amount', true);
        return await self.model('balance_log').db(self.db.db()).add({
          admin_id: self.user.uid,
          user_id: data.id,
          type: 2,
          time: new Date().valueOf(),
          amount: data.balance,
          amount_log: amount_log,
          note: `管理员（${await get_nickname(self.user.uid)}）为您充值，充值的金额为：${data.balance} 元`
        });
      });

      if (insertId) {
        return this.success({ name: '充值成功!' });
      } else {
        return this.fail('充值失败!');
      }
    } else {
      const id = this.get('ids');
      const name = await get_nickname(id);
      this.assign('name', name);
      this.assign('id', id);
      this.meta_title = '会员充值';
      return this.display();
    }
  }
  /**
     * adduser
     * 添加用户
     * @returns {Promise|*}
     */
  async adduserAction () {
    if (this.isPost) {
      const data = this.post();
      data.user_active = 1;
      if (data.password != data.repassword) {
        return this.fail('两次填入的密码不一致');
      }
      data.password = encryptPassword(data.password);
      data.reg_time = new Date().getTime();
      data.overduedate = 0;
      data.status = 1;
      data.zhucestatus = 0;
      data.username = data.mobile;
      const res = await this.db.add(data);
      if (res) {
        return this.success({ name: '添加成功！' });
      } else {
        return this.fail('添加失败!');
      }
    } else {
      this.meta_title = '添加用户';
      return this.display();
    }
  }

  // 会员注销
  async cancelAction () {
    if (this.isPost) {
      const id = this.post('id');
      const remarkData = this.post();
      remarkData.remark_time = new Date().getTime();
      remarkData.remark_name = this.user.id;
      remarkData.foreign_key = id;
      remarkData.model_name = this.tactive;
      delete remarkData.id;
      const remarksId = await this.model('remarks').add(remarkData);
      const updateDate = { status: -1, cancel_remark_id: remarksId };
      const res = await this.db.where({ id: id }).update(updateDate);
      if (res) {
        return this.success({ name: '注销成功！' });
      } else {
        return this.fail('注销失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.assign('operation', '注销');
      return this.display('admin/remark_public');
    }
  }

  /**
     * 编辑用户
     * @returns {PreventPromise}
     */
  async edituserAction () {
    if (this.isPost) {
      const data = this.post();
      // 删除头像
      if (data.delavatar == 1) {
        const uploadPath = think.resource + '/upload/avatar/' + data.id;
        const path = think.isFile(uploadPath + '/avatar.png');
        if (path) {
          think.rmdir(uploadPath, false);
        }
      }

      if (think.isEmpty(data.password) && think.isEmpty(data.repassword)) {
        delete data.password;
      } else {
        if (data.password != data.repassword) {
          return this.fail('两次填入的密码不一致');
        }
        data.password = encryptPassword(data.password);
      }
      if (data.vip == 1) {
        if (think.isEmpty(data.overduedate)) {
          data.overduedate = new Date();
        }
        data.overduedate = new Date(data.overduedate).getTime();
      } else {
        data.overduedate = 0;
        data.vip = 0;
      }
      // 添加角色
      if (data.is_admin == 1) {
        const addrole = await this.model('auth_user_role').where({ user_id: data.id }).thenAdd({ user_id: data.id, role_id: data.role_id });
        // console.log(addrole);
        if (addrole.type == 'exist') {
          await this.model('auth_user_role').update({ id: addrole.id, role_id: data.role_id });
        }
      }
      const res = await this.db.update(data);

      if (res) {
        return this.success({ name: '编辑成功！' });
      } else {
        return this.fail('编辑失败!');
      }
    } else {
      // 获取公司信息
      /* if (think.isEmpty(this.companyList)) {
        const resp = await this.requestOA('executeQuery', { sql: 'select * from hrmsubcompany where nvl(canceled,0)<>1 order by id' });
        if (resp.errno == 0) {
          //this.assign('company', resp.data.list);
          this.companyList = resp.data.list;
        }
      } */

      const id = this.get('id');
      const user = await this.model('member').find(id);
      // 不能修改超级管理员的信息
      if (!this.is_admin) {
        if (in_array(id, this.config('user_administrator'))) {
          const error = this.controller('cmswing/error');
          return error.noAction('您无权操作！');
        }
      }
      this.assign('user', user);
      const url = [];
      // url = JSON.parse(user.sfzzmpic)[0]+JSON.parse(user.sfzfmpic)[0]+JSON.parse(user.yyzzpic)[0]+JSON.parse(user.khxkzpic)[0];
      if (user.sfzzmpic) {
        url.push(JSON.parse(user.sfzzmpic)[0]);
      }
      if (user.sfzfmpic) {
        url.push(JSON.parse(user.sfzfmpic)[0]);
      }
      if (user.yyzzpic) {
        url.push(JSON.parse(user.yyzzpic)[0]);
      }
      if (user.khxkzpic) {
        url.push(JSON.parse(user.khxkzpic)[0]);
      }
      console.log(url);
      this.assign('url', url);
      // console.log(user);
      // 所属管理组
      if (user.is_admin == 1) {
        const roleid = await this.model('auth_user_role').where({ user_id: user.id }).getField('role_id', true);
        this.assign('roleid', roleid);
      }
      // 会员组
      const usergroup = await this.model('member_group').select();
      this.assign('usergroup', usergroup);
      // 获取管理组
      const role = await this.model('auth_role').where({ status: 1 }).select();
      this.assign('role', role);
      this.meta_title = '编辑用户';
      return this.display();
    }
  }

  async editshenheAction () {
    if (this.isPost) {
      const data = this.post();
      data.zhucestatus = 2;
      data.shenheshijian = new Date().valueOf();
      const res = await this.db.update(data);
      // {username:data1.username,org_type:data1.org_type,user_code:data1.user_code}//.where({id:data1.id})
      if (res == 1) {
        return this.success({ name: '编辑成功！' });
      } else {
        return this.fail('编辑失败!');
      }
    } else {
      const id = this.get('id');
      const user = await this.model('member').find(id);
      // 内核公司列表
      const zzjg = await this.model('zzjg').select();
      this.assign('zzjg', zzjg);
      // 不能修改超级管理员的信息
      if (!this.is_admin) {
        if (in_array(id, this.config('user_administrator'))) {
          const error = this.controller('cmswing/error');
          return error.noAction('您无权操作！');
        }
      }
      this.assign('user', user);
      // 所属管理组
      if (user.is_admin == 1) {
        const roleid = await this.model('auth_user_role').where({ user_id: user.id }).getField('role_id', true);
        this.assign('roleid', roleid);
      }
      const url = [];
      // url = JSON.parse(user.sfzzmpic)[0]+JSON.parse(user.sfzfmpic)[0]+JSON.parse(user.yyzzpic)[0]+JSON.parse(user.khxkzpic)[0];
      if (user.sfzzmpic) {
        url.push(JSON.parse(user.sfzzmpic)[0]);
      }
      if (user.sfzfmpic) {
        url.push(JSON.parse(user.sfzfmpic)[0]);
      }
      if (user.yyzzpic) {
        url.push(JSON.parse(user.yyzzpic)[0]);
      }
      if (user.khxkzpic) {
        url.push(JSON.parse(user.khxkzpic)[0]);
      }

      console.log(url);
      /* let url = await this.model('ext_attachment_pic').where({id: ['IN', [user.sfzzmpic, user.sfzfmpic,user.yyzzpic,user.khxkzpic]]}).getField('path'); */
      // console.log('url===='+url);
      this.assign('url', url);
      // 会员组
      const usergroup = await this.model('member_group').select();
      this.assign('usergroup', usergroup);
      // 获取管理组
      const role = await this.model('auth_role').where({ status: 1 }).select();
      this.assign('role', role);
      this.meta_title = '编辑用户';
      return this.display();
    }
  }

  /**
     * 显示用户信息
     * @returns {PreventPromise}
     */
  async showuserAction () {
    const id = this.get('id');
    const user = await this.model('member').find(id);
    this.assign('user', user);
    // 会员组
    const usergroup = await this.model('member_group').where({ groupid: user.groupid }).find();
    this.assign('usergroup', usergroup);
    const url = [];
    if (user.sfzzmpic) {
      url.push(JSON.parse(user.sfzzmpic)[0]);
    }
    if (user.sfzfmpic) {
      url.push(JSON.parse(user.sfzfmpic)[0]);
    }
    if (user.yyzzpic) {
      url.push(JSON.parse(user.yyzzpic)[0]);
    }
    if (user.khxkzpic) {
      url.push(JSON.parse(user.khxkzpic)[0]);
    }
    this.assign('url', url);
    this.meta_title = '个人信息';
    return this.display();
  }
  /**
     * userdel
     * 用户删除
     * @returns {Promise|*}
     */
  async userdelAction () {
    const id = this.para('ids');
    // console.log(id);
    let res;
    // 判断是否是管理员，如果是不能删除;
    if (await this.isadmin(id)) {
      return this.fail('不能删除管理员!');
    } else {
      // 逻辑删除
      res = await this.db.where({ id: ['IN', id] }).delete();
      // res = await this.db.where({id: ['IN', id]}).update({status: -1});
      if (res) {
        return this.success({ name: '删除成功！' });
      } else {
        return this.fail('删除失败！');
      }
    }
  }

  // 用户实名认证驳回
  async shenhebohuiAction () {
    if (this.isPost) {
      const id = this.post('id');
      const remarkData = this.post();
      remarkData.remark_time = new Date().getTime();
      remarkData.remark_name = this.user.id;
      remarkData.foreign_key = id;
      remarkData.model_name = this.tactive;
      delete remarkData.id;
      const remarksId = await this.model('remarks').add(remarkData);
      const updateDate = { zhucestatus: -1, reject_remarks_id: remarksId };
      const res = await this.db.where({ id: id }).update(updateDate);
      if (res) {
        return this.success({ name: '驳回成功！' });
      } else {
        return this.fail('驳回失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.assign('operation', '驳回');
      return this.display('admin/remark_public');
    }
  }

  /**
     * 改变角色状态
     * @returns {Promise|*}
     */
  async chstaAction () {
    const res = await this.db.update(this.get());
    if (res) {
      return this.json(res);
    }
  }

  /**
     * 注册异步验证用户数据
     * @returns {Promise|*}
     */
  async parsleyAction () {
    // 验证
    const data = this.get();
    // console.log(data);
    const res = await this.db.where(data).find();
    // console.log(res);
    if (think.isEmpty(res)) {
      return this.json(1);
    } else {
      return this.json(0);
    }
  }

  // 获取头像
  async avatarAction () {
    const uid = this.get('uid') || this.user.uid;
    var uploadPath = think.resource + '/upload/avatar/' + uid;
    const path = think.isFile(uploadPath + '/' + '/avatar.png');
    let pic;
    if (path) {
      pic = fs.readFileSync(uploadPath + '/' + '/avatar.png');
    } else {
      pic = fs.readFileSync(think.resource + '/upload/avatar/avatar.jpg');
    }
    this.header('Content-Type', 'image/png');
    return this.body = pic;
  }

  /**
   * 修改个人密码
   */
  async updatepsAction () {
    const user = await this.session('userInfo');
    console.log('user=' + user);
    if (this.isPost) {
      const id = this.post('id');
      const yuanpassword = this.post('yuanpassword');
      console.log('yuanpassword=' + yuanpassword);
      const res = await this.model('member').where({ id: user.id, password: encryptPassword(yuanpassword) }).count();
      console.log('res=' + res);
      if (res == 1) {
        const password = this.post('password');
        const repassword = this.post('repassword');
        if (password != repassword) {
          return this.fail('两次密码输入不一致！');
        }
        const update_time = new Date().valueOf();
        const voids = await this.model('member').where({ id: id }).update({ password: encryptPassword(password), update_time: update_time });
        console.log('voids=' + voids);
        if (voids) {
          return this.success({ name: '修改密码成功！' });
        } else {
          // location.reload();
          return this.fail({ name: '操作失败！' });
        }
      } else {
        return this.fail('原密码输入错误！');
      }
    } else {
      this.assign('user', user);
      console.log('user=' + user);
      this.meta_title = '修改个人密码';
      return this.display();
    }
  }
  // 导出
  async exportAction () {
    const modelexp = this.get('modelexp');
    let map;
    let data;
    if (modelexp == 1) {
      map = { 'status': ['>', -1], is_admin: 0 };
      map.zhucestatus = ['in', [-1, 2]];
      if (!think.isEmpty(this.get('real_name'))) {
        map.real_name = ['like', '%' + this.get('real_name') + '%'];
      }
      if (!think.isEmpty(this.get('mobile'))) {
        map.mobile = this.get('mobile');
      }
      if (!think.isEmpty(this.get('gsmc'))) {
        map.gsmc = ['like', '%' + this.get('gsmc') + '%'];
      }
      if (!think.isEmpty(this.get('groupid'))) {
        map.groupid = this.get('groupid');
      }
      data = await this.db.where(map).order('id DESC').select();
    } else if (modelexp == 2) {
      map = { 'status': ['>', -1], is_admin: 0 };
      if (!think.isEmpty(this.get('real_name'))) {
        map.real_name = ['like', '%' + this.get('real_name') + '%'];
      }
      if (!think.isEmpty(this.get('mobile'))) {
        map.mobile = this.get('mobile');
      }
      if (!think.isEmpty(this.get('gsmc'))) {
        map.gsmc = ['like', '%' + this.get('gsmc') + '%'];
      }
      if (!think.isEmpty(this.get('groupid'))) {
        map.groupid = this.get('groupid');
      }
      data = await this.db.where(map).order('id DESC').select();
    } else if (modelexp == 3) {
      const query = unflatten(this.get());
      map = await getmap(this.tactive, query);
      map.status = -1;
      map.is_admin = 0;
      map.cancel_remark_id = ['!=', null];
      delete map.modelexp;
      data = await this.db.where(map).order('id DESC').select();
    } else if (modelexp == 4) {
      if (!think.isEmpty(this.get('real_name'))) {
        map.real_name = ['like', '%' + this.get('real_name') + '%'];
      }
      if (!think.isEmpty(this.get('mobile'))) {
        map.mobile = this.get('mobile');
      }
      if (!think.isEmpty(this.get('gsmc'))) {
        map.gsmc = ['like', '%' + this.get('gsmc') + '%'];
      }
      data = await this.model('member_log').where(map).order('id DESC').select();
    } else if (modelexp == 5) {
      const query = this.get();
      delete query.page;
      delete query.modelexp;
      const list = await this.model('cmswing/member').listactionsafeOrder(query, this.get('page') || 1, 20);
      data = list.data;
    } else {
      return this.fail('参数传递失败！');
    }

    const res = await this.model('cmswing/member').export_user(data, modelexp);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + 'MemberExport' + '.xlsx');
    this.ctx.body = res;
  }

  // 用户管控列表
  async actionsafeAction () {
    const query = this.get();
    delete query.page;
    const data = await this.model('cmswing/member').listactionsafeOrder(query, this.get('page') || 1, 20);
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '用户管控';
    this.tactive = 'actionsafe';
    return this.display();
  }
  async listproblemAction () {
    const id = this.get('id');
    if (!think.isNumberString(id)) {
      return this.fail('参数出错');
    }
    const data = await this.model('cmswing/member').listproblem(id);
    const html = this.pagination(data);
    this.assign('list', data);
    this.meta_title = '问题单列表';
    return this.display();
  }

  // 冻结会员
  async freezeAction () {
    if (this.isPost) {
      const id = this.post('id');
      const user = await this.db.where({ id: id }).find();
      if (user.status == 0) {
        return this.fail('该用户已处于冻结状态，重复操作！');
      }
      const freeze_limit = this.post('freeze_limit');
      const locked_time = new Date().getTime();
      const remarkData = this.post();
      remarkData.remark_time = new Date().getTime();
      remarkData.remark_name = this.user.id;
      remarkData.foreign_key = id;
      remarkData.model_name = this.tactive;
      delete remarkData.id;
      delete remarkData.freeze_limit;
      const remarksId = await this.model('remarks').add(remarkData);
      const updateDate = { freeze_status: 1, cancel_remark_id: remarksId, freeze_limit: freeze_limit, locked_time: locked_time };
      const res = await this.db.where({ id: id }).update(updateDate);
      if (res) {
        return this.success({ name: '冻结成功！' });
      } else {
        return this.fail('冻结失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.assign('operation', '冻结');
      return this.display();
    }
  }
  // 解冻会员
  async thawAction () {
    if (this.isPost) {
      const id = this.post('id');
      const opening_time = new Date().getTime();
      const remarkData = this.post();
      remarkData.remark_time = new Date().getTime();
      remarkData.remark_name = this.user.id;
      remarkData.foreign_key = id;
      remarkData.model_name = this.tactive;
      delete remarkData.id;
      const remarksId = await this.model('remarks').add(remarkData);
      const updateDate = { freeze_status: 0, opening_remark_id: remarksId, opening_time: opening_time };
      const res = await this.db.where({ id: id }).update(updateDate);
      const user = await this.db.where({ id: id }).find();
      const log = {
        user_id: user.id,
        real_name: user.real_name,
        mobile: user.mobile,
        is_admin: user.is_admin,
        groupid: user.groupid,
        org_type: user.org_type,
        user_code: user.user_code,
        gsmc: user.gsmc,
        locked_time: user.locked_time,
        freeze_limit: user.freeze_limit,
        opening_time: user.opening_time,
        reject_remarks_id: user.reject_remarks_id,
        manage_remark_id: user.manage_remark_id,
        cancel_remark_id: user.cancel_remark_id,
        opening_remark_id: user.opening_remark_id
      };
      const addlog = await this.model('member_log').add(log);
      if (!addlog) {
        return this.fail('日志新增失败！');
      }
      if (res) {
        return this.success({ name: '冻结成功！' });
      } else {
        return this.fail('冻结失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.assign('operation', '解冻');
      return this.display('admin/remark_public');
    }
  }

  // 已冻结列表
  async frozenAction () {
    const data = await this.db.where({ freeze_status: 1, is_admin: 0, cancel_remark_id: ['!=', null] }).page(this.get('page') || 1, 20).order('id DESC').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '已冻结列表';
    this.tactive = 'actionsafe';
    return this.display();
  }
  // 已解冻列表
  async thawlistAction () {
    const query = unflatten(this.get());
    const map = await getmap('member_log', query);
    const data = await this.model('member_log').where(map).page(this.get('page') || 1, 20).order('id DESC').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '已解冻列表';
    this.tactive = 'actionsafe';
    return this.display();
  }
};
